<script setup lang="ts">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { useI18n } from '@/hooks/web/useI18n'
import { ElButton, ElMessageBox, ElMessage } from 'element-plus'
import { Dialog } from '@/components/Dialog'
import Edit from './components/Edit.vue'
import See from './components/See.vue'
import { spFeedSeeExcelApi } from '@/api/forms'
import { Table } from '@/components/Table'
import {
  spFeedListApi,
  spFeedAddAdminApi,
  spFeedEditApi,
  spFeedDelApi,
  spFeedConfirmApi,
  spFeedBatchConfirmApi
} from '@/api/sp/feed'
import { useTable } from '@/hooks/web/useTableTest'
import { ref, reactive, unref } from 'vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useIcon } from '@/hooks/web/useIcon'
import { useCache } from '@/hooks/web/useCache'
const { wsCache } = useCache()
const dict: any = wsCache.get('dict')
// const userInfo: any = wsCache.get('userInfo')
const getDictLabel = (type, value) => {
  let data = dict[type].find((item) => {
    return item.value == value
  })
  return data ? data.label : ''
}
const FormsNumber = ref(0)
const dialogTableVisible = ref(false)
const Load = ref(false)
const arr: any = ref([])
const saveLoading = ref(false) //保存中的状态
const iconEdit = useIcon({ icon: 'ep:edit' })
const iconSee = useIcon({ icon: 'ep:view' })
const iconDel = useIcon({ icon: 'ep:delete' })
const iconFile = useIcon({ icon: 'material-symbols:drive-file-move-sharp' })
const iconExcel = useIcon({ icon: 'file-icons:microsoft-excel' })
const { register, tableObject, methods } = useTable<
  {
    total: number
    list: any[]
  },
  any
>({
  getListApi: spFeedListApi,
  response: {
    data: 'data',
    count: 'count'
  }
})

const { getList, setSearchParams } = methods

getList()

const { t } = useI18n()
const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'id',
    label: '主键',
    fixed: 'left',
    width: 60,
    table: {
      show: true
    },
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'pasture_org_name',
    label: '所属牧场',
    search: {
      show: true
    }
  },
  {
    field: 'code',
    label: '喂养单号',
    search: {
      show: true
    }
  },
  {
    field: 'forage_formula_name',
    label: '饲料配方',
    search: {
      show: true
    }
  },
  {
    field: 'type',
    label: '喂养类型',
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('feed_type', cellValue)
    },
    width: 150,
    search: {
      component: 'Select',
      componentProps: {
        options: dict.feed_type
      },
      show: true
    }
  },
  {
    field: 'number',
    label: '喂养数'
  },
  {
    field: 'feed_time',
    label: '喂养时间',
    width: 180,
    form: {
      show: true,
      component: 'DatePicker',
      componentProps: {
        disabled: true,
        type: 'datetime',
        valueFormat: 'YYYY-MM-DD HH:mm:ss'
      }
    },
    search: {
      show: true,
      component: 'DatePicker',
      componentProps: {
        'is-range': true,
        'unlink-panels': true,
        rangeSeparator: 'To',
        type: 'daterange',
        valueFormat: 'YYYY-MM-DD HH:mm:ss'
      }
    }
  },
  {
    field: 'state',
    label: '状态',
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('feed_state', cellValue)
    },
    width: 80,
    search: {
      component: 'Select',
      componentProps: {
        options: dict.feed_state
      },
      show: true
    }
  },
  {
    field: 'note',
    label: '备注',
    search: {
      show: false
    }
  },
  {
    field: 'create_user_name',
    label: '创建人',
    width: 150,
    search: {
      show: true
    }
  },
  {
    field: 'action',
    width: 200,
    fixed: 'right',
    label: t('tableDemo.action'),
    form: {
      show: false
    },
    detail: {
      show: false
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const dialogVisible = ref(false)

const dialogTitle = ref('')

const actionType = ref('')

const action = async (type: string, row: any = {}) => {
  actionType.value = type
  switch (type) {
    case 'edit':
      dialogTitle.value = '编辑'
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'add':
      dialogTitle.value = '新增'
      tableObject.currentRow = {
        is_stop: '0'
      }
      dialogVisible.value = true
      break
    case 'see':
      dialogTitle.value = '查看'
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'excel':
      arr.value = []
      const { getSelections } = methods
      const selections = await getSelections()
      FormsNumber.value = selections.length
      dialogTableVisible.value = true
      selections.forEach((element, i) => {
        feedSeeExcel(element, i)
      })
      break
    case 'file':
      ElMessageBox.confirm(`喂养后不可以修改删除，是否喂养？`, '喂养', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          file(Number(row.id))
        })
        .catch(() => {})
      break
    case 'del':
      ElMessageBox.confirm(`删除该喂养记录？`, '删除', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          del(Number(row.id))
        })
        .catch(() => {})
      break
    default:
      console.log('未知类型')
  }
}

const feedSeeExcel = async (element, i) => {
  let { data }: any = await spFeedSeeExcelApi({
    request: {
      id: element.id,
      my_org_id: wsCache.get('userInfo').default_org_id
    },
    layout_data: {
      file_name: '喂养单饲料详情',
      column_cell_start: 'A6',
      column_value: 'detailed',
      column_data: [
        {
          title: '序号',
          width: 5,
          cell_type: 'key'
        },
        {
          title: '饲料名称',
          width: 80,
          cell_type: 'string',
          give_type: 'variable',
          give_value: 'forage_name'
        },
        {
          title: '饲料总数量',
          width: 30,
          cell_type: 'string',
          give_type: 'variable',
          give_value: 'weight'
        },
        {
          title: '比例',
          width: 30,
          cell_type: 'string',
          give_type: 'variable',
          give_value: 'ratio'
        }
      ],
      custom: [
        {
          cell_type: 'string',
          cell: 'A1:D1',
          give_type: 'format',
          give_value: '喂养单饲料详情',
          horizontal: 'center',
          border: true,
          size: '16'
        },
        {
          cell_type: 'string',
          cell: 'A2:B2',
          give_type: 'format',
          give_value: '牧场名称：${pasture_name}',
          horizontal: 'left',
          border: true,
          size: '12'
        },
        {
          cell_type: 'string',
          cell: 'C2:D2',
          give_type: 'format',
          give_value: '单号：${code}',
          horizontal: 'left',
          border: true,
          size: '12'
        },
        {
          cell_type: 'string',
          cell: 'A3:B3',
          give_type: 'format',
          give_value: '类型：${dict.feed_type.${type}}',
          horizontal: 'left',
          border: true,
          size: '12'
        },
        {
          cell_type: 'string',
          cell: 'C3:D3',
          give_type: 'format',
          give_value: '状态：${dict.feed_state.${state}}',
          horizontal: 'left',
          border: true,
          size: '12'
        },
        {
          cell_type: 'string',
          cell: 'A4:B4',
          give_type: 'format',
          give_value: '喂养配方：${forage_formula_name}',
          horizontal: 'left',
          border: true,
          size: '12'
        },
        {
          cell_type: 'string',
          cell: 'C4:D4',
          give_type: 'format',
          give_value: '喂养时间：${feed_time}',
          horizontal: 'left',
          border: true,
          size: '12'
        },
        {
          cell_type: 'string',
          cell: 'A5:D5',
          give_type: 'template',
          give_value: '喂养栏位：{% for k,v in enclosureData %}{{ v.name }} {% endfor %}',
          horizontal: 'left',
          border: true,
          size: '12'
        }
      ],
      dict: ['feed_type', 'feed_state']
    }
  })
    .catch(() => {})
    .finally(() => {})
  if (data) {
    arr.value[i] = {}
    arr.value[i].url = data.url
    arr.value[i].code = element.code
  }
}
const Export = (index) => {
  window.open(index)
}
const del = async (id) => {
  let delRes = await spFeedDelApi({ id })
    .catch(() => {})
    .finally(() => {})
  if (delRes) {
    getList()
  }
}

const file = async (id) => {
  let delRes = await spFeedConfirmApi({ id })
    .catch(() => {})
    .finally(() => {})
  if (delRes) {
    getList()
  }
}

const editRef = ref<ComponentRef<typeof Edit>>()
const save = async () => {
  const edit = unref(editRef)
  const dataInfo = await edit?.data
  if (dataInfo.number > 0) {
  } else {
    ElMessage.error('所选资产不能为0')
  }

  switch (actionType.value) {
    case 'add':
      const data = (await edit?.getFormData()) as any
      console.log(data, 'data')
      await edit?.elFormRef?.validate(async (isValid) => {
        if (isValid) {
          const data = (await edit?.getFormData()) as any
          data.my_dept_id = wsCache.get('userInfo').default_dept_id
          let props: any = {}
          props = {
            my_dept_id: wsCache.get('userInfo').default_dept_id,
            pasture_org_id: data.pasture_org_id,
            pasture_dept_id: data.pasture_dept_id,
            pasture_user_id: data.pasture_user_id,
            feed_time: data.feed_time,
            forage_formula_id: data.forage_formula_id,
            number: data.number,
            threshold: data.threshold,
            type: '2',
            detailed: data.detailed,
            selected: data.selectData,
            note: data.note
          }
          let res = await spFeedAddAdminApi(props)
            .catch(() => {})
            .finally(() => {
              saveLoading.value = false
            })
          if (res) {
            dialogVisible.value = false
            tableObject.currentPage = 1
            getList()
          }
        }
      })
      break
    case 'edit':
      await edit?.elFormRef?.validate(async (isValid) => {
        if (isValid) {
          const data = (await edit?.getFormData()) as any
          data.my_dept_id = wsCache.get('userInfo').default_dept_id
          let props: any = {}
          props = {
            id: data.id,
            admin_org_id: data.admin_org_id,
            admin_dept_id: data.admin_dept_id,
            admin_user_id: data.admin_user_id,
            pasture_org_id: data.pasture_org_id,
            pasture_dept_id: data.pasture_dept_id,
            pasture_user_id: data.pasture_user_id,
            feed_time: data.feed_time,
            forage_formula_id: data.forage_formula_id,
            number: data.number,
            threshold: data.threshold,
            type: '2',
            detailed: data.detailed,
            selected: data.selectData,
            note: data.note
          }
          let res = await spFeedEditApi(props)
            .catch(() => {})
            .finally(() => {
              saveLoading.value = false
            })
          if (res) {
            dialogVisible.value = false
            tableObject.currentPage = 1
            getList()
          }
        }
      })
      break
    default:
      console.log('未知类型')
  }
}

// const delData = async () => {}
const delLoading = ref(false)
const batchData = async () => {
  const { getSelections } = methods
  const selections = await getSelections()
  const ids = selections.map((v) => v.id)
  delLoading.value = true
  ElMessageBox.confirm('喂养后不可删除修改，是否喂养？', '喂养', {
    confirmButtonText: t('common.delOk'),
    cancelButtonText: t('common.delCancel'),
    type: 'warning'
  })
    .then(async () => {
      let res = await spFeedBatchConfirmApi({ ids: ids })
        .catch(() => {})
        .finally(() => {
          delLoading.value = false
        })
      if (res) {
        getList()
      }
    })
    .catch(() => {})
}
</script>

<template>
  <ContentWrap>
    <Search :schema="allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams" />
    <div class="mb-10px">
      <ElButton type="primary" @click="action('add')">新增</ElButton>
      <ElButton type="success" @click="batchData()">批量喂养</ElButton>
      <ElButton color="#626aef" :icon="iconExcel" @click="action('excel')" title="批量导出"
        >批量导出</ElButton
      >
    </div>
    <Table
      v-model:pageSize="tableObject.pageSize"
      v-model:currentPage="tableObject.currentPage"
      :columns="allSchemas.tableColumns"
      :data="tableObject.tableList"
      :loading="tableObject.loading"
      :border="true"
      :pagination="{
        total: tableObject.count
      }"
      @register="register"
    >
      <template #action="{ row }">
        <ElButton circle :icon="iconSee" @click="action('see', row)" title="查看" />
        <ElButton
          v-if="row.state == 1"
          circle
          :icon="iconEdit"
          @click="action('edit', row)"
          title="编辑"
        />
        <ElButton
          v-if="row.state == 1"
          circle
          :icon="iconDel"
          @click="action('del', row)"
          title="删除"
        />
        <ElButton
          v-if="row.state == 1"
          circle
          :icon="iconFile"
          @click="action('file', row)"
          title="确认归档"
        />
        <!-- <ElButton circle :icon="iconExcel" @click="action('excel', row)" title="导出" /> -->
      </template>
    </Table>
  </ContentWrap>
  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Edit v-if="actionType == 'add'" ref="editRef" :form-schema="allSchemas.formSchema" />
    <Edit
      v-if="actionType == 'edit'"
      ref="editRef"
      :form-schema="allSchemas.formSchema"
      :current-row="tableObject.currentRow"
      :id="tableObject.currentRow.id"
    />
    <See
      v-if="actionType == 'see'"
      :id="tableObject.currentRow.id"
      :detail-schema="allSchemas.detailSchema"
    />
    <template #footer>
      <ElButton
        v-if="actionType == 'add' || actionType == 'edit'"
        type="primary"
        :loading="saveLoading"
        @click="save()"
      >
        保存
      </ElButton>
      <ElButton @click="dialogVisible = false">关闭</ElButton>
    </template>
  </Dialog>
  <el-dialog v-model="dialogTableVisible" title="喂养单导出">
    <el-table v-loading="Load" style="width: 100%" v-show="Load" />
    <div style="margin: 20px" v-for="(item, index) in arr" :key="index">
      <span style="margin: 20px">喂养单 - {{ item.code }}</span>
      <ElButton type="primary" @click="Export(item.url)">导出</ElButton>
    </div>
  </el-dialog>
</template>
